﻿using AduSkin.Controls.Metro;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using HsServerHa.Core.Http;
using HsServerHa.Core;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.SQLite;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HsServerHa.UserControls.Dialog
{
    /// <summary>
    /// AddAlarmPush.xaml 的交互逻辑
    /// </summary>
    public partial class AddAlarmPush : UserControl
    {
        public AddAlarmPush()
        {
            InitializeComponent();
        }

        private async void btn_Setting_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(API.Text))
            {
                AduMessageBoxs.Show("请输入API地址");
                return;
            }
            if (string.IsNullOrEmpty(Method.Text))
            {
                AduMessageBoxs.Show("请选择请求方式");
                return;
            } 
            if (string.IsNullOrEmpty(ParamStr.Text))
            {
                AduMessageBoxs.Show("请填写API参数！");
                return;
            }

            if (string.IsNullOrEmpty(IsEnable.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")))
            {
                AduMessageBoxs.Show("请选择是否启用");
                return;
            }


            if (App.isMaster == null)
            {
                AduMessageBoxs.Show("程序配置有误，请初始化配置");
                return;
            }

            //查询绑定信息
            var bindList = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();

            var bindFirst = bindList?.FirstOrDefault();
            if (bindFirst == null)
            {
                AduMessageBoxs.Show("程序配置有误，请初始化配置");
                return;
            }

            MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定设置吗？", "系统提示!", "确定", "取消");
            if (dr == MessageBoxResult.OK)
            {
                var parms = new AlarmPushManageEntity
                {
                    ProgramKey = GeneratePrimaryKeyIdHelper.GetPrimaryKeyId().ToString(),
                    Api = API.Text,
                    Method = Method.Text,
                    ParamStr = ParamStr.Text, 
                    IsEnable = IsEnable.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", ""),
                    CreateTime = DateTime.Now.ToString()
                };
                var result = new HttpResponseResultModel<object>();
                if (App.isMaster.Value)
                {
                    var slavePath = $"http://{bindFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";

                    #region 上传程序数据给从机

                    result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(slavePath +
                   (ConfigurationManager.AppSettings["postAddAlarmPushData"]?.ToString() ?? "postAddAlarmPushData"), JsonConvert.SerializeObject(parms));



                    #endregion
                }
                else
                {
                    var masterPath = $"http://{App.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
        
                    #region 上传程序数据给主机

                    result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(masterPath +
                        (ConfigurationManager.AppSettings["postAddAlarmPushData"]?.ToString() ?? "postAddAlarmPushData"), JsonConvert.SerializeObject(parms));
                    #endregion
                }
                if (result == null)
                {
                    AduMessageBoxs.Show("添加失败");
                    LoggerHelper.SetInfo("添加失败:" + JsonConvert.SerializeObject(parms), "报警推送管理");
                    return;
                }
                else
                {
                    if (result.IsSuccess)
                    {
                        SQLiteHelper.ExecuteSql($"insert into AlarmPushManage (ProgramKey,Api,Method,ParamStr,IsEnable,CreateTime)" +
                                $" values('{parms.ProgramKey}','{API.Text}','{Method.Text}','{ParamStr.Text}','{IsEnable.SelectedValue?.ToString().Replace("System.Windows.Controls.ComboBoxItem: ", "")}','{DateTime.Now.ToString()}')");

                        AduMessageBoxs.Show("添加成功！");
                        WeakReferenceMessenger.Default.Send(new ValueChangedMessage<string>("刷新报警数据"), "RefreshAlarm");

                        LoggerHelper.SetInfo("新增报警推送数据:" + JsonConvert.SerializeObject(parms), "报警推送管理");

                        var control = this.Parent as ContentControl;
                        Window win = Window.GetWindow(control);
                        var title = win?.Title;
                        if (title != null)
                        {
                            if (title != "HsServerHa")
                            {
                                win.Close();
                            }

                        }

                    }
                    else
                    {
                        AduMessageBoxs.Show("添加失败");
                        LoggerHelper.SetInfo("添加失败:" + JsonConvert.SerializeObject(parms), "报警推送管理");
                        return;
                    }
                }
            }
        }

        private void TestRequest_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(API.Text))
            {
                AduMessageBoxs.Show("请输入API地址");
                return;
            }
            if (string.IsNullOrEmpty(Method.Text))
            {
                AduMessageBoxs.Show("请选择请求方式");
                return;
            }
            if (string.IsNullOrEmpty(ParamStr.Text))
            {
                AduMessageBoxs.Show("请填写API参数！");
                return;
            }
            if (Method.Text=="Post")
            {
                var result = HttpService.Instance.Post(API.Text, ParamStr.Text.Replace("#Params#", "告警测试")).Result;
                if (result != null)
                {
                    AduMessageBoxs.Show($"{result.ToString()}");
                }
                else
                {
                    AduMessageBoxs.Show("接口异常，请检查！");
                    return;
                }
            }
          
        }
    }
}
